package com.hupu.jrs.ui.imagepreview

import android.content.Context
import android.content.Intent
import android.net.Uri
import com.facebook.cache.common.CacheKey
import com.facebook.imagepipeline.cache.DefaultCacheKeyFactory
import com.facebook.imagepipeline.core.ImagePipelineFactory
import com.facebook.imagepipeline.request.ImageRequest
import com.hupu.jrs.components.okhttp.OkHttpHelper
import com.hupu.jrs.injector.PerActivity
import com.hupu.jrs.util.ConfigUtil
import com.hupu.jrs.util.FormatUtil
import com.hupu.jrs.util.StringUtil
import com.hupu.jrs.util.ToastUtil
import java.io.File
import java.io.InputStream
import javax.inject.Inject
import okio.BufferedSink
import okio.Okio
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.functions.Func1
import rx.schedulers.Schedulers

/**
 * Created by sll on 2016/4/29.
 */
@PerActivity
class ImagePreviewPresenter @Inject
constructor(private val mOkHttpHelper: OkHttpHelper, private val mContext: Context) : ImagePreviewContract.Presenter {

    override fun saveImage(url: String) {
        Observable.just(url)
                .map { s -> getImageBytesFromLocal(Uri.parse(s)) }
                .map(Func1<InputStream, File> { inputStream ->
                    if (inputStream != null) {
                        val fileName = FormatUtil.getFileNameFromUrl(url)
                        val target = File(ConfigUtil.getPicSavePath(mContext), fileName)
                        if (target.exists()) {
                            return@Func1 target
                        }
                        try {
                            val sink = Okio.buffer(Okio.sink(target))
                            sink.writeAll(Okio.source(inputStream))
                            sink.close()
                            return@Func1 target
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }

                    }
                    null
                })
                .map(Func1<File, File> { file ->
                    if (file != null && file.exists()) {
                        return@Func1 file
                    }
                    try {
                        mOkHttpHelper.httpDownload(url, file)
                        return@Func1 file
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }

                    null
                })
                .doOnNext { file ->
                    if (file != null && file.exists()) {
                        scanPhoto(file)
                    }
                }
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { file ->
                    if (file != null && file.exists()) {
                        ToastUtil.showToast("保存成功")
                    } else {
                        ToastUtil.showToast("保存失败，请重试")
                    }
                }
    }

    private fun getImageBytesFromLocal(loadUri: Uri?): InputStream? {
        if (loadUri == null) {
            return null
        }
        val cacheKey = DefaultCacheKeyFactory.getInstance()
                .getEncodedCacheKey(ImageRequest.fromUri(loadUri), null)
        try {
            if (ImagePipelineFactory.getInstance().mainFileCache.hasKey(cacheKey)) {
                return ImagePipelineFactory.getInstance()
                        .mainFileCache
                        .getResource(cacheKey)
                        .openStream()
            }
            if (ImagePipelineFactory.getInstance().smallImageFileCache.hasKey(cacheKey)) {
                return ImagePipelineFactory.getInstance()
                        .smallImageFileCache
                        .getResource(cacheKey)
                        .openStream()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return null
    }

    private fun scanPhoto(file: File?) {
        val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
        val contentUri = Uri.fromFile(file)
        mediaScanIntent.data = contentUri
        mContext.sendBroadcast(mediaScanIntent)
    }

    override fun copyImagePath(url: String) {
        StringUtil.copy(mContext, url)
    }

    override fun attachView(view: ImagePreviewContract.View) {

    }

    override fun detachView() {

    }
}
